import { Injectable, Inject, forwardRef } from '@nestjs/common';
import { CreateCooperateDto } from './dto/create-cooperate.dto';
import { Cooperate } from './cooperate.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like, Raw, In } from 'typeorm';
import { RemoveCooperateDto } from './dto/remove-cooperate.dto';

@Injectable()
export class CooperateService {
  constructor(
    @InjectRepository(Cooperate)
    private cooperateRepository: Repository<Cooperate>,
  ) {}

  // 增加
  async create(createCooperateDto: CreateCooperateDto): Promise<any> {
    const { createdAt } = createCooperateDto;
    createCooperateDto.createdAt = createdAt || new Date();
    createCooperateDto.updatedAt = new Date();

    delete createCooperateDto.id;

    return await this.cooperateRepository.save(createCooperateDto);
  }

  // 删除
  async delete(removeCooperateDto: RemoveCooperateDto): Promise<any> {
    const { ids } = removeCooperateDto;

    return this.cooperateRepository.delete(ids);
  }

  // 更新
  async update(updateCooperateData): Promise<any> {
    const { id, updateCooperateDto } = updateCooperateData;
    updateCooperateDto.updatedAt = new Date();

    return await this.cooperateRepository.update(id, updateCooperateDto);
  }

  // 列表
  async findAll(query: any): Promise<any> {
    const { keyword, pageId, page = 1, limit = 10 } = query;
    const skip = (page - 1) * limit;

    let params = {
      skip,
      take: limit,
    };

    let whereParams = {};

    if (keyword) {
      whereParams = [
        {
          name: Like(`%${keyword}%`),
        },
        {
          phone: Like(`%${keyword}%`),
        },
      ];
    }
    if (pageId) {
      const ids = Array.isArray(pageId) ? pageId : [pageId];

      whereParams = keyword
        ? [
            {
              pageId: In(ids),
              name: Like(`%${keyword}%`),
            },
            {
              pageId: In(ids),
              phone: Like(`%${keyword}%`),
            },
          ]
        : { pageId: In(ids) };
    }

    params = Object.assign(
      params,
      {
        where: whereParams,
      },
      {
        order: {
          updatedAt: 'DESC',
        },
      },
    );

    const [data, total] = await this.cooperateRepository.findAndCount(params);

    return {
      total,
      data,
    };
  }

  // 根据ID查找
  async findOneById(id: string): Promise<any> {
    return this.cooperateRepository
      .createQueryBuilder()
      .where([{ route: id }, { id }])
      .getOne();
  }

  // 数量
  async getCount(query: any) {
    const { pageId } = query;

    let params = {};
    let whereParams = {};

    if (pageId) {
      const ids = Array.isArray(pageId) ? pageId : [pageId];
      whereParams = {
        pageId: In(ids),
      };
    }

    params = Object.assign(params, {
      where: whereParams,
    });

    return await this.cooperateRepository.count(params);
  }
}
